<template>
	<view>
		<view class="page__content">
			<up-navbar :fixed="false" title="报工" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff">
			</up-navbar>

			<view class="page__content__main" :style="{ overflow: formColumnOrRow == 'row' ? 'hidden' : 'auto' }">
				<up-form labelPosition="left" :model="formData" :rules="rules" ref="uForm">
					<view :style="{display:'flex',flexDirection:formColumnOrRow}" style="height: 100%;">

						<view :class="{'flex-auto':formColumnOrRow == 'row' }">

							<up-form-item labelWidth="120" label="报工单号" borderBottom>
								<view class="iptView">
									<up-input v-model="formData.BGBillNo" placeholder="自动生成" readonly
										border="none"></up-input>
								</view>
							</up-form-item>

							<up-form-item v-if="FCJType == 1" labelWidth="120" label="派工单号" prop="BillNO" borderBottom
								required>
								<view class="iptView" @click="openBaseScreen('派工单号','radio')">
									<up-input v-model="formData.BillNO" placeholder="请扫码或选择" readonly
										border="none"></up-input>
								</view>

								<template #right>
									<view class="x-f">
										<up-icon name="arrow-right" color="#999" size="18"></up-icon>
										<up-icon name="scan" @click="OpenScanBtn" size="20" color="#999"></up-icon>
									</view>
								</template>
							</up-form-item>

							<up-form-item v-if="FCJType == 2" labelWidth="120" label="工单号" prop="WoBillNO" borderBottom
								required>
								<view class="iptView" @click="openBaseScreen('工单号','radio')">
									<up-input v-model="formData.WoBillNO" readonly placeholder="请扫码或选择"
										border="none"></up-input>
								</view>

								<template #right>
									<view class="x-f">
										<up-icon name="arrow-right" color="#999" size="18"></up-icon>
										<up-icon name="scan" @click.stop="OpenScanBtn" size="20" color="#999"></up-icon>
									</view>
								</template>
							</up-form-item>

							<up-form-item labelWidth="120" label="报工类型" prop="JobDocTypeName"
								:disabled="!uni.$utils.isEmpty(formData.BGBillNo)" borderBottom required>
								<view class="iptView" @click="openBaseScreen('报工类型','radio')">
									<up-input v-model="formData.JobDocTypeName" readonly placeholder="请选择"
										border="none"></up-input>
								</view>

								<template #right>
									<up-icon name="arrow-right" color="#999" size="18"></up-icon>
								</template>
							</up-form-item>

							<!-- <up-form-item labelWidth="120" label="销售单号" borderBottom>
								<view class="iptView">
									<up-input v-model="formData.SoBillNO" readonly border="none"></up-input>
								</view>
							</up-form-item> -->

							<up-form-item labelWidth="120" label="产品信息" borderBottom>
								<view class="iptView">
									<up-input v-model="formData.ProductCode" readonly border="none"></up-input>
								</view>
							</up-form-item>

							<up-form-item labelWidth="120" label="生产车间" prop="FWorkshopName" borderBottom required>
								<view class="iptView" @click="openBaseScreen('生产车间','radio')">
									<up-input v-model="formData.FWorkshopName" readonly placeholder="请选择"
										border="none"></up-input>
								</view>

								<template #right>
									<up-icon name="arrow-right" color="#999" size="18"></up-icon>
								</template>
							</up-form-item>

							<up-form-item labelWidth="120" label="工序名称" prop="ProcedureName" borderBottom required>
								<view class="iptView" @click="openBaseScreen('工序','radio')">
									<up-input v-model="formData.ProcedureName" readonly placeholder="请选择"
										border="none"></up-input>
								</view>

								<template #right>
									<up-icon name="arrow-right" color="#999" size="18"></up-icon>
								</template>
							</up-form-item>

							<view class="x-f">
								<up-form-item labelWidth="120" label="派工数" prop="FPlanQty" borderBottom
									style="flex: 1;">
									<view class="iptView">
										<up-input v-model="formData.FPlanQty" readonly border="none"></up-input>
									</view>
								</up-form-item>

								<up-form-item labelWidth="120" label="可报工数" prop="ReportQty" borderBottom
									style="flex: 1;">
									<view class="iptView">
										<up-input v-model="formData.ReportQty" readonly border="none"></up-input>
									</view>
								</up-form-item>
							</view>

							<up-form-item labelWidth="120" label="计时计件" prop="PieceTimeName" borderBottom required
								style="flex: 1;">
								<view class="iptView" @click="openBaseScreen('计时计件','radio')">
									<up-input v-model="formData.PieceTimeName" readonly placeholder="请选择"
										border="none"></up-input>
								</view>

								<template #right>
									<up-icon name="arrow-right" color="#999" size="18"></up-icon>
								</template>
							</up-form-item>

							<up-form-item labelWidth="120" label="作业员" prop="EmplName" required borderBottom
								style="flex: 1;">
								<view class="iptView" @click="openBaseScreen('作业员','check')">
									<up-input v-model="formData.EmplName" readonly placeholder="请选择"
										border="none"></up-input>
								</view>

								<template #right>
									<up-icon name="arrow-right" color="#999" size="18"></up-icon>
								</template>
							</up-form-item>

							<!-- <view style="padding: 0 6px 0 16px;">
								<up-line></up-line>
							</view> -->

							<up-form-item labelWidth="120" label="班次" prop="ShiftName" borderBottom required>
								<view class="iptView" @click="openBaseScreen('班次','radio')">
									<up-input v-model="formData.ShiftName" readonly placeholder="请选择"
										border="none"></up-input>
								</view>

								<template #right>
									<up-icon name="arrow-right" color="#999" size="18"></up-icon>
								</template>
							</up-form-item>
						</view>

						<view v-if="formColumnOrRow == 'row'" style="background-color: #f9f9f9;width: 10px;"></view>

						<view :class="{'flex-auto':formColumnOrRow == 'row' }">

							<up-form-item labelWidth="120" label="合格数" borderBottom>
								<view class="iptView">
									<up-input v-model="formData.FDailyQtt" type="number" placeholder="请输入合格数"
										border="none"></up-input>
								</view>
								<template #right>
									<up-icon name="edit-pen-fill" color="#999" size="18"></up-icon>
								</template>
							</up-form-item>

							<up-form-item labelWidth="120" label="不良数" borderBottom>
								<view class="iptView">
									<up-input v-model="formData.FNgQty" type="number" readonly border="none"></up-input>
								</view>
								<!-- <template #right>
									<up-icon name="edit-pen-fill" color="#999" size="18"></up-icon>
								</template> -->
							</up-form-item>

							<view class="x-f">
								<up-form-item labelWidth="120" label="工废数" style="flex: 1;" borderBottom>
									<view class="iptView">
										<up-input v-model="formData.IndustrialWaste" @blur="InputNums" type="number"
											border="none"></up-input>
									</view>
									<template #right>
										<up-icon name="edit-pen-fill" color="#999" size="18"></up-icon>
									</template>
								</up-form-item>

								<up-form-item labelWidth="120" label="料废数" style="flex: 1;" borderBottom>
									<view class="iptView">
										<up-input v-model="formData.MaterialWaste" @blur="InputNums" type="number"
											border="none"></up-input>
									</view>
									<template #right>
										<up-icon name="edit-pen-fill" color="#999" size="18"></up-icon>
									</template>
								</up-form-item>
							</view>

							<!-- <view style="padding: 0 6px 0 16px;">
								<up-line></up-line>
							</view> -->

							<up-form-item labelWidth="120" label="报工时长" :prop="formData.PieceTime == 1 ? 'ManHour' : ''"
								borderBottom :required="formData.PieceTime != 0" style="margin-top: 10px;">
								<view class="x-f" style="width: 100%;">
									<view class="x-f" style="flex: 1;padding: 0 10px;">
										<up-input style="flex: 1;" type="number" v-model="formData.Hour"
											inputAlign="center" @input="ChangeDate" border="none"
											@blur="BlurDateIpt('hour')"></up-input>
										<text>小时</text>

										<up-input style="flex: 1;" type="number" v-model="formData.Minute"
											inputAlign="center" @input="ChangeDate" border="none"
											@blur="BlurDateIpt('minute')"></up-input>
										<text>分钟</text>
									</view>

									<view class="x-f" @click="OpenChoiceDate"
										style="height: 100%;min-width: 30px;justify-content: center;">
										<up-icon name="arrow-right" color="#999" size="18"></up-icon>
									</view>
								</view>
							</up-form-item>

							<!-- 起止时间 -->
							<up-form-item labelWidth="120" label="开始时间" :required="formData.PieceTime != 0"
								borderBottom>
								<view class="iptView" @click="ChoiceTime('start')">
									<up-input v-model="formData.StartTime" readonly border="none"></up-input>
								</view>
								<template #right>
									<up-icon name="calendar" color="#999" size="18"></up-icon>
								</template>
							</up-form-item>

							<up-form-item labelWidth="120" label="结束时间" :required="formData.PieceTime != 0"
								borderBottom>
								<view class="iptView" @click="ChoiceTime('end')">
									<up-input v-model="formData.EndTime" readonly border="none"></up-input>
								</view>
								<template #right>
									<up-icon name="calendar" color="#999" size="18"></up-icon>
								</template>
							</up-form-item>

							<up-form-item labelWidth="120" label="模具编号" style="margin-top: 10px;" borderBottom>
								<view class="iptView" @click="openBaseScreen('模具编号','radio')">
									<up-input v-model="formData.MoludCode" readonly placeholder="请选择"
										border="none"></up-input>
								</view>

								<template #right>
									<up-icon name="arrow-right" color="#999" size="18"></up-icon>
								</template>
							</up-form-item>

							<up-form-item labelWidth="120" label="设备/产线" style="flex: 1;" borderBottom>
								<view class="iptView" @click="openBaseScreen('设备','radio')">
									<up-input v-model="formData.EquipmentName" readonly placeholder="请选择"
										border="none"></up-input>
								</view>

								<template #right>
									<up-icon name="arrow-right" color="#999" size="18"></up-icon>
								</template>
							</up-form-item>

							<up-form-item labelWidth="120" label="备注">
								<view class="iptView" style="padding: 10px 20px 0;width: 100%;">
									<up-textarea v-model="formData.FRemarks" placeholder="请输入内容" count
										maxlength="150"></up-textarea>
								</view>
							</up-form-item>
						</view>

					</view>
				</up-form>
			</view>

			<view class="page__content__bottom" :style="uni.$utils.disposeSafeBottomFun()">
				<button :disabled="!enabledSubmitBtn" v-if="isEdit && formData.FDailyOutputDeID"
					class="content_bottom_primary_plainBtn CommonBtnSize" @click="WorkInit">继续报工</button>

				<button :disabled="!enabledSubmitBtn" v-if="!formData.FDailyOutputDeID"
					class="content_bottom_primary_Btn" style="width: 90%;margin: 0 auto !important;"
					@click="SubmitBtn">提交</button>

				<button :disabled="!enabledSubmitBtn"
					v-if="formData.FDailyOutputDeID && !formData.Approve && ApproveBack('修改')"
					class="content_bottom_primary_Btn CommonBtnSize" style="margin-left: 10px !important;"
					@click="EditBtn('Edit')">修改</button>

				<button :disabled="!enabledSubmitBtn"
					v-if="formData.FDailyOutputDeID && hasApprove && formData.Approve && ApproveBack('撤审')"
					class="content_bottom_primary_Btn CommonBtnSize" style="margin-left: 10px !important;"
					@click="EditBtn('Audit')">
					撤审
				</button>

				<!-- 当 formData.Approve 为 false 时，显示“审核”按钮 -->
				<button :disabled="!enabledSubmitBtn"
					v-if="formData.FDailyOutputDeID && hasApprove && !formData.Approve && ApproveBack('审核')"
					class="content_bottom_primary_Btn CommonBtnSize" style="margin-left: 10px !important;"
					@click="EditBtn('Audit')">
					审核
				</button>
			</view>
		</view>

		<!-- 悬浮按钮 -->
		<m-drag-button :style="{ opacity: BtnShow ? 1 : 0, }" v-show="!formData.Approve" :isDock="true"
			:existTabBar="true" :initialBottom="80" @btnClick="OpenScanBtn">
			<template #BtnContent>
				<up-icon name="scan" color="#fff" size="54rpx"></up-icon>
			</template>
		</m-drag-button>

		<!-- 操作菜单 -->
		<up-action-sheet :safeAreaInsetBottom="true" :closeOnClickOverlay="true" :closeOnClickAction="true"
			@close="closeContinuePopup" :actions="ContinueData" @select="selectClick" :show="ShowContinuePopup"
			cancelText="取消"></up-action-sheet>

		<!-- 扫设备带出可报工工序 -->
		<up-popup :show="showPopupByDevice" :round="20" mode="center" :closeOnClickOverlay="false"
			@close="closeDevicePopup" :safe-area-inset-bottom="false" style="background-color: transparent;">
			<view class="f-dc popup__content"
				style="width: 80vw;background-color: #f9f9f9;border-radius: 20rpx;overflow: hidden;">
				<z-paging ref="paging" :auto="false" :fixed="false" v-model="ScanByDeviceList"
					@query="getMainInfoByDevice" height="60vh">
					<!-- 需要固定在顶部不滚动的view放在slot="top"的view中，如果需要跟着滚动，则不要设置slot="top" -->
					<!-- 注意！此处的z-tabs为独立的组件，可替换为第三方的tabs，若需要使用z-tabs，请在插件市场搜索z-tabs并引入，否则会报插件找不到的错误 -->
					<template #top>
						<u-navbar :fixed="false" :title="'设备-工序' + '(' + ScanByDeviceList.length + ')'"
							:titleStyle="{'font-size':'16px'}" :autoBack="false" leftIcon=" " :safeAreaInsetTop="false">
							<view class="u-nav-slot" slot="right">
								<uni-icons color="#fff" type="close" size="30" @click="closeDevicePopup"></uni-icons>
							</view>
						</u-navbar>
					</template>

					<view class="common__box__list-card" v-for="(item,index) in ScanByDeviceList" :key="index"
						@click="ChoiceDeviceToProcedure(index)" style="margin-bottom: 10rpx;">

						<view style="position: absolute;right: 20rpx;top: 20rpx;">
							<view style="position: relative;">
								<checkbox class="CheckBox" :checked="item.checked" activeBackgroundColor="#51d0d0"
									activeBorderColor="#51d0d0">
								</checkbox>

								<view
									style="width: 100%;height: 100%;background-color: transparent;position: absolute;z-index: 9;left: 0;top: 0;">
								</view>

							</view>
						</view>

						<view class="common__box__list-card__content">
							<view class="common__box__list-card__content__field" v-for="(row,ind) in scanDeviceInfo"
								:key="ind">
								<view class="common__box__list-card__content__field__label">
									<text>{{row.keyName}}：</text>
								</view>
								<view class="common__box__list-card__content__field__value">
									<text>{{item[row.keyValue]}}</text>
								</view>
							</view>

						</view>
					</view>

					<template #bottom>
						<view class="popup__content__bottom x-f">
							<button class="content_bottom_primary_plainBtn CommonBtnSize"
								@click="closeDevicePopup">取消</button>
							<button class="content_bottom_primary_Btn CommonBtnSize"
								@click="ChoiceProcedure_Config">确认</button>
						</view>
					</template>

				</z-paging>



			</view>
		</up-popup>

		<!-- 报工时长时间选择器 -->
		<up-datetime-picker class="DateTimerPick" ref="datetimePickerBG" title="选择报工时长" :show="showTimePickerBG"
			v-model="DatetimeDataBG" mode="time" :closeOnClickOverlay="true" @close="ClosePickerBG"
			@cancel="ClosePickerBG" @confirm="ConfirmTimeBG" :formatter="formatter"></up-datetime-picker>

		<!-- 起止时间选择器 -->
		<up-datetime-picker ref="datetimePicker" :title="PickerTitle" :show="showTimePicker" v-model="DatetimeData"
			mode="datetime" :closeOnClickOverlay="true" @close="ClosePicker" @cancel="ClosePicker"
			@confirm="ConfirmTime" :formatter="formatter"></up-datetime-picker>

		<!-- 加载动画 -->
		<m-loading :text="loadingConfig.text" :value="loadingConfig.show" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted, computed, nextTick } from 'vue'
	import { onLoad, onReady, onShow, onUnload } from '@dcloudio/uni-app'
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, PromiseRequestByUrl, onAllComplete, onError } = useRequestQueue();
	import { useMainStore, useUserStore, usePermissionStore, useTicketStore } from '@/store';
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();
	const ticketStore = useTicketStore();

	defineOptions({
		options: {
			styleIsolation: 'shared'
		}
	});

	let enabledSubmitBtn = ref(false);	// 控制按钮是否启用
	let loadingConfig = reactive({
		text: "正在渲染",
		show: false,
	});

	const FCJType = computed(() => {	// 公司报工类型 1、派工 2、工单
		return ticketStore.FCJType;
	})

	let isEdit = ref(false);	// 是否是列表进来的
	let hasApprove = ref(false);	// 是否有审核权限

	let formData = reactive<any>({
		FDailyOutputDeID: null,
		QrCode: null,
		WoBillNO: null, // 工单号
		BillNO: null, // 派工单号

		JobDocTypeName: null, // 报工类型
		JobDocTypeID: null, // 报工类型ID

		FWorkshopName: null, // 车间
		FWorkshopID: null, // 车间ID

		ProcedureName: null, // 工序
		ProcedureID: null, // 工序ID

		WoPROCID: null, // 工单工序

		PieceTimeName: '', // 计时计件
		PieceTime: '', // 计时计件

		EmplName: null, // 作业员
		EmplID: null,

		FPlanQty: null, // 派工书
		WCQty: null, // 完成数
		ReportQty: null, // 可报工数
		FDailyQtt: null, // 填写合格数
		FNgQty: null, // 
		IndustrialWaste: null, // 工废数
		MaterialWaste: null, // 料废数

		ShiftName: null, // 班次
		ShiftID: null,

		MoludName: null, // 模具
		MoludCode: null, // 模具
		MoludID: null,
		MoludTypeID: null,

		EquipmentName: '',
		EquipmentCode: null, // 设备/产线
		EquipmentID: null,

		Hour: 0, // 小时
		Minute: 0, // 分钟
		StartTime: null, // 开始时间
		EndTime: null, // 结束时间

		Approve: false, // 是否审核

		FRemarks: '',
	});

	const rules = {
		'WoBillNO': { // 工单号
			type: 'string',
			required: true,
			message: '工单号不能为空',
			trigger: ['change']
		},
		'BillNO': { // 派工单号
			type: 'string',
			required: true,
			message: '派工单号不能为空',
			trigger: ['change']
		},
		'FWorkshopName': { // 生产车间
			type: 'string',
			required: true,
			message: '生产车间不能为空',
			trigger: ['change']
		},
		'ProcedureName': { // 工序
			type: 'string',
			required: true,
			message: '工序不能为空',
			trigger: ['change']
		},
		'PieceTimeName': { // 计时计件
			type: 'string',
			required: true,
			message: '计时计件不能为空',
			trigger: ['change']
		},
		'EmplName': { // 作业员
			type: 'string',
			required: true,
			message: '作业员不能为空',
			trigger: ['change']
		},
		'ShiftName': { // 班次
			type: 'string',
			required: true,
			message: '班次不能为空',
			trigger: ['change']
		},
		'ManHour': { // 报工时长
			type: 'string',
			required: true,
			message: '报工时长不能为空',
			trigger: ['change']
		},
	}

	let foundNode = ref<any>(null);
	// 获取页面按钮权限
	for (const module of permissionStore.moduleInfoAll) {
		if (module.TreeTypeName === '生产管理') {
			for (const node of module.Node) {
				if (node.APFunName === '新建报工') {
					foundNode.value = JSON.parse(JSON.stringify(node));
					break; // 找到后立即退出内层循环  
				}
			}
			if (foundNode.value) {
				break;
			}
		}
	}

	// let primaryType = ref(false); // 左右布局
	let formColumnOrRow = ref('column');

	let BtnApprove = ref<any>([]); // 权限数组

	const deviceInfo = uni.getSystemInfoSync();
	let sysDeviceInfo = {}; // 默认空对象避免判空异常

	try {
		const storedData = uni.getStorageSync('sysDeviceInfo');
		if (storedData) sysDeviceInfo = JSON.parse(storedData);
	} catch (error) {
		console.error('sysDeviceInfo 解析失败:', error);
	}

	const isWideScreen = deviceInfo.windowWidth >= 1000;
	const type = mainStore.systemConfig.sysDeviceInfo.scanDeviceType === 'GKJ' || isWideScreen ? 'row' : 'column';

	formColumnOrRow.value = type;
	BtnApprove.value = foundNode.value['IconApprove'];

	GetUserWorkshop();

	const PieceTimeNameData = [{
		PieceTimeName: '计件',
		PieceTime: 0
	},
	{
		PieceTimeName: '计时',
		PieceTime: 1
	}];

	let showTimePickerBG = ref(false);	// 时间选择器弹层
	let DatetimeDataBG = ref<string | null>(null);	// 时间选择器时间

	let DatetimeData = ref<number>(Number(new Date()));	// 时间选择器时间
	let showTimePicker = ref(false); // 时间选择器弹层显示
	let TimeType = ref(''); // 区分时间 start - 开始 ， end - 结束
	let PickerTitle = ref(''); // 时间弹层标题
	let BtnShow = ref(false); // 按钮样式初始化有问题，等加载完再显示

	let showPopupByDevice = ref(false); // 扫设备码带出的工序弹层
	let DeviceID = ref<string | null>(null); // 扫描的设备ID
	let ScanByDeviceList = ref<any>([]);  // 弹层列表数据
	let scanDeviceInfo = [
		{ keyName: '工单编号', keyValue: 'WoBillNO' },
		{ keyName: '派工单号', keyValue: 'BillNO' },
		{ keyName: '产品', keyValue: 'ProductName' },
		{ keyName: '规格', keyValue: 'ProductSpec' },
		{ keyName: '工序', keyValue: 'ProcedureName' },
		{ keyName: '设备', keyValue: 'EquipmentName' },
		{ keyName: '可报数量', keyValue: 'ReportQty' },
	]
	let SelectScanByDeviseIndex = ref<number | null>(null); // 点击的卡片数据索引


	let ShowContinuePopup = ref(false); // 操作菜单
	const ContinueData = ref<any>([{
		name: '空白报工',
		value: 0
	}, {
		name: '连续报工',
		value: 1
	}]);

	function WorkInit() {
		ShowContinuePopup.value = true;
	}

	function closeContinuePopup() {
		ShowContinuePopup.value = false;
	}

	function SubmitBtn(Type = 'Submit') { // 提交按钮
		if (!enabledSubmitBtn.value) return;
		loadingConfig.text = "正在校验";
		loadingConfig.show = true;
		enabledSubmitBtn.value = false;

		uForm.value?.validate().then(async (res : any) => {
			loadingConfig.text = "校验成功，准备提交";

			let ManHour = +formData.Hour + +formData.Minute / 60;
			let obj = {

				Define1: formData.JobDocTypeID, // 单据类型

				SoOrderID: formData.SoOrderID || 0, // 销售订单主表ID
				SoOrderDeID: formData.SoOrderDeID, // 销售订单子表ID
				ProductID: formData.ProductID, // 产品ID

				FWorkshopID: formData.FWorkshopID, // 生产车间
				ProcedureID: formData.ProcedureID, // 工序ID

				PieceTime: formData.PieceTime, // 计时计件

				FProcessMan: formData.EmplID, // 作业员ID
				ShiftID: formData.ShiftID, // 班次

				FDailyQtt: +formData.FDailyQtt || 0, // 合格数量
				IndustrialWaste: formData.IndustrialWaste || 0, // 工费数
				MaterialWaste: formData.MaterialWaste || 0, // 料废数
				FNgQty: +formData.FNgQty || 0, // 不良数量

				SCDate: dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'), // 生产日期
				WoOrderID: formData.WoOrderID, // 工单ID


				FCJType: FCJType.value, // 单据类别
				ManHour: ManHour, // 工时
				EquipmentID: formData.EquipmentID || 0, // 设备ID
				MoludID: formData.MoludID || 0, // 模具ID
				FRemarks: formData.FRemarks, // 子表备注

				JobOrderID: formData.JobOrderID, // 派工单ID
				JobPROCID: formData.JobPROCID, // 派工单子表ID
				WoPROCID: formData.WoPROCID, // 工单工序

				JobPROCAssignEQID: formData.JobPROCAssignEQID || 0, // 派工单指定ID
				WoPROCAssignEQID: formData.WoPROCAssignEQID || 0, // 派工单指定ID
			};

			loadingConfig.text = "正在提交";
			const save_back = await request({
				url: 'XGD_DailyOutputBG_2',
				method: 'POST',
				data: obj
			});

			if (save_back.status == 200) {
				if (save_back.data?.ds.length && save_back.data?.ds[0]?.status == 200) {
					loadingConfig.text = "提交成功";
					formData.FDailyOutputDeID = save_back.data.ds[0].FDailyOutputDeID;
					GetEchoData(save_back.data.ds[0].FDailyOutputDeID);
					// 刷新报工列表
					uni.$emit('refreshPage_works')
				} else {
					loadingConfig.show = false;
					enabledSubmitBtn.value = true;
					uni.$utils.layer.alert(save_back.data?.ds[0]?.msg);
				}
			}

		}).catch((error : any) => {
			console.log(error)
			loadingConfig.show = false;
			enabledSubmitBtn.value = true;
			uni.$utils.layer.alert('请完善表单信息');
		});
	}

	function EditBtn(Type : any) { // 修改按钮
		if (!enabledSubmitBtn.value) return;
		loadingConfig.show = true;
		loadingConfig.text = "正在校验";
		enabledSubmitBtn.value = false;

		uForm.value?.validate().then((res : any) => {
			loadingConfig.text = "校验成功，准备提交";

			if (formData.Approve) {
				ApproveBtn();
				return
			}

			let ManHour = +formData.Hour + +formData.Minute / 60;

			let obj : any = {
				FDailyOutputID: formData.FDailyOutputID || 0, // 主表ID
				FDailyOutputDeID: formData.FDailyOutputDeID || 0, // 子表ID

				Define1: formData.JobDocTypeID, // 单据类型

				SoOrderID: formData.SoOrderID || 0, // 销售订单主表ID
				SoOrderDeID: formData.SoOrderDeID || 0, // 销售订单子表ID
				ProductID: formData.ProductID, // 产品ID

				FWorkshopID: formData.FWorkshopID, // 生产车间
				ProcedureID: formData.ProcedureID, // 工序ID

				PieceTime: formData.PieceTime, // 计时计件

				FProcessMan: formData.EmplID, // 作业员ID
				ShiftID: formData.ShiftID, // 班次

				FDailyQtt: +formData.FDailyQtt || 0, // 合格数量
				IndustrialWaste: formData.IndustrialWaste || 0, // 工费数
				MaterialWaste: formData.MaterialWaste || 0, // 料废数
				FNgQty: +formData.FNgQty || 0, // 不良数量

				SCDate: dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'), // 生产日期
				WoOrderID: formData.WoOrderID, // 工单ID


				FCJType: FCJType.value, // 单据类别
				ManHour: ManHour, // 工时
				EquipmentID: formData.EquipmentID, // 设备ID
				MoludID: formData.MoludID, // 模具ID
				FRemarks: formData.FRemarks, // 子表备注
			};

			// let submitCmd = 'GD_DailyOutputUpdate';
			if (FCJType.value == 1) {

				obj['JobOrderID'] = formData.JobOrderID || 0; // 派工单ID
				obj['JobPROCID'] = formData.JobPROCID || 0; // 派工单子表ID

				obj['WoPROCAssignEQID'] = formData.WoPROCAssignEQID;
				obj['JobPROCAssignEQID'] = formData.JobPROCAssignEQID;
				obj['WoPROCID'] = formData.WoPROCID || 0; // 工单工序

			} else if (FCJType.value == 2) {
				obj['WoPROCID'] = formData.WoPROCID || 0; // 工单工序
			}

			loadingConfig.text = "正在提交";
			request({
				config: {
				},
				url: 'XGD_DailyOutputUpdate_2',
				method: 'POST',
				data: obj,
				success(ret : any) {

					if (ret.data.ds[0].status == 500) {
						uni.$utils.layer.alert(ret.data.ds[0].msg);
						loadingConfig.text = "提交失败";
						loadingConfig.show = false;
						enabledSubmitBtn.value = true;
					} else {
						if (Type == 'Audit') {
							ApproveBtn();
						} else {
							loadingConfig.text = "提交成功";
							loadingConfig.show = false;
							enabledSubmitBtn.value = true;

							// 调用回显接口，处于修改状态
							formData.FDailyOutputDeID = ret.data.ds[0].FDailyOutputDeID;
							GetEchoData(ret.data.ds[0].FDailyOutputDeID);

							// 刷新报工列表
							uni.$emit('refreshPage_works')
						}
					}
				}
			});

		}).catch((errors : any) => {
			console.log(JSON.stringify(errors))
			if (Array.isArray(errors)) {
				uni.$utils.layer.alert('请完善表单');
			}
			loadingConfig.show = false;
			enabledSubmitBtn.value = true;
		});
	}

	function ApproveBtn() { // 审核、撤审按钮

		let obj = {
			KeyID: formData.FDailyOutputID,
			Type: formData.Approve ? -1 : 1,
			UserName: userStore.UserInfo.UserName,
			FCJType: FCJType.value
		};

		loadingConfig.text = formData.Approve ? "正在撤审" : "正在审核";

		request({
			config: {
			},
			url: 'XGD_ApproveSubByFCJType',
			method: 'POST',
			data: obj,
			success(ret : any) {
				if (ret.status == 200) {

					if (ret.data.ds[0].status == 500) {
						loadingConfig.text = formData.Approve ? "撤审失败" : "审核失败";
						uni.$utils.layer.alert(ret.data.ds[0].msg);
						loadingConfig.show = false;
						enabledSubmitBtn.value = true;
					} else {
						// 刷新报工列表
						uni.$emit('refreshPage_works')
						loadingConfig.show = false;
						enabledSubmitBtn.value = true;

						loadingConfig.text = formData.Approve ? '撤审成功' : '审核成功';
						GetEchoData(formData.FDailyOutputDeID);
					}

				}

			}
		})
	}

	function ApproveBack(str : string) {

		let Type = BtnApprove.value.some((item : any) => {
			return item.MenuName == str
		})

		return Type;
	}

	function InitCreateFun() { // 如果切换工单号或派工单号，将界面初始化
		isEdit.value = false; // 将状态却换成非编辑状态
		hasApprove.value = false; // 关闭审核

		Object.keys(formData).forEach((key) => {
			if (!['EmplID', 'EmplName', 'PieceTime', 'PieceTimeName',
				'ShiftID', 'ShiftName', 'JobDocTypeName', 'JobDocTypeID'
			].includes(key)) {

				if (formData[key] == null) {
					formData[key] = null;
				} else if (Array.isArray(formData[key])) {
					formData[key] = [];
				} else if (typeof formData[key] === 'object') {
					formData[key] = {};
				} else {
					formData[key] = '';
				}
			}
		});

	}

	let UserWorkshopID = ref(0);

	let FilterFormData = reactive({ // 主表多选字段数据存储
		EmplIDData: [],
		EmplIDDataJoin: ''
	});

	interface pagingInstance {
		reload : () => void;
		refresh : () => void;
		complete : () => void;
		setLocalPaging : () => void;
	}
	let paging = ref<pagingInstance | any>(null);

	interface uFormInstance {
		validate : () => void;
		setRules : any;
	}
	let uForm = ref<uFormInstance | any>(null);

	function InitFormData() {
		let date = uni.$utils.dateFormat(new Date(), 'yyyy-MM-dd  hh:mm');
		formData.StartTime = date;
		formData.EndTime = date;
		console.log(formData);

		// 赋值默认计时计件数据
		formData = Object.assign(formData, PieceTimeNameData[0]);
		console.log(formData);

		// 获取报工类型
		GetPGD_GetBGType();

		// 获取默认班次
		GetDroplist_Shift();

		getEmplInfo();
	}

	function GetUserWorkshop() {

		let UserID = userStore.UserInfo.UserID;

		let sql = `select isnull(FWorkshopID,0) as FWorkshopID from SYS_User where UserID=${UserID}`;
		//console.log(sql);
		try {
			requestByUrl({
				config: {
					baseURL: '/SQLData/QuerySql'
				},
				url: '',
				method: 'POST',
				data: {
					sql: sql
				}, success(ret : any) {

					if (ret.status == 200) {
						if (ret.data?.ds?.length && ret.data?.ds[0]?.hasOwnProperty("FWorkshopID")) {
							UserWorkshopID.value = ret.data.ds[0].FWorkshopID;
						}
					}

				}
			})

		} catch (e) {
			UserWorkshopID.value = 0;
		}

	}

	function InputNums() { // 工费、料废失焦触发
		let IndustrialWaste = +formData.IndustrialWaste || 0;
		let MaterialWaste = +formData.MaterialWaste || 0;
		// 合计报废数量
		formData.FNgQty = IndustrialWaste + MaterialWaste;
		console.log(formData.FNgQty);
	}

	function GetPGD_GetBGType() {	// 获取默认报工类型

		request({
			config: {
			},
			url: 'PGD_GetBGType',
			method: 'POST',
			data: {}, success(ret : any) {
				if (ret.status == 200) {
					let data = ret.data.ds.map((item : any) => {
						return {
							...item,
							JobDocTypeName: item.TypeName,
						}
					});

					formData = Object.assign(formData, data[0]);
				}
			}
		});

	}

	function getXGD_GetWorkApprove() { // 修改状态，获取是否允许审核

		request({
			config: {
			},
			url: 'XGD_GetWorkApprove',
			method: 'POST',
			data: {
				UserID: userStore.UserInfo.UserID
			}, success(ret : any) {
				if (ret.status == 200) {
					let _hasApprove = ret.data.ds.some((item : any) => {
						return item.IsWorkApprove
					})
					// console.log(hasApprove);
					hasApprove.value = _hasApprove;
				}
			}
		});

	}

	function GetEchoData(id : number) { // 获取回显的数据

		request({
			config: {
			},
			url: 'XGD_DailyOutputmxjl_2',
			method: 'POST',
			data: {
				FDailyOutputDeID: id
			}, success(ret : any) {
				if (ret.status == 200) {
					// 定义计件计时显示值
					let PieceTimeName = PieceTimeNameData.find(
						item => item.PieceTime === ret.data?.ds?.[0]?.PieceTime
					)?.PieceTimeName || '';
					// 定义时间显示值
					let ManHour = ret.data.ds[0]['ManHour'];
					let hour = Math.floor(ManHour); // 取整数部分作为小时数
					let minute = Math.round((ManHour - hour) * 60); // 小数部分乘以60得到分钟数
					ret.data.ds[0]['Hour'] = hour;
					ret.data.ds[0]['Minute'] = minute;


					ret.data.ds[0]['PieceTimeName'] = PieceTimeName;
					ret.data.ds[0]['JobDocTypeName'] = ret.data.ds[0]['TypeName'];
					ret.data.ds[0]['JobDocTypeID'] = ret.data.ds[0]['Define1'];
					ret.data.ds[0]['EmplName'] = ret.data.ds[0]['FProcessManName'];
					ret.data.ds[0]['EmplID'] = ret.data.ds[0]['FProcessMan'];

					ret.data.ds[0]['FPlanQty'] = ret.data.ds[0]['FPlanNum'];
					// ret.data.ds[0]['FDailyQtt'] = ret.data.ds[0]['FDailyQtt'];
					// ret.data.ds[0]['ReportQty'] = ret.data.ds[0]['ReportQty'];
					ret.data.ds[0]['ManHour'] = String(ret.data.ds[0]['ManHour']);


					formData = Object.assign(formData, ret.data.ds[0]);

					let EmplID = [] as any;
					let EmplName = [];
					if (formData.EmplID) {
						console.log(typeof formData.EmplID);
						EmplID = String(formData.EmplID).split(',');
						EmplName = formData.EmplName.split(',');
						FilterFormData.EmplIDData = EmplName.map((item : any, index : any) => {
							return {
								EmplName: item,
								EmplID: +EmplID[index]
							}
						});
						FilterFormData.EmplIDDataJoin = formData.EmplName;

					}

					isEdit.value = true;
					getXGD_GetWorkApprove()

					loadingConfig.show = false;
					enabledSubmitBtn.value = true;

				} else {

					loadingConfig.show = false;
					enabledSubmitBtn.value = true;
				}
			}
		});

	}

	function ChoiceTime(type : string) { // 点击起止时间

		TimeType.value = type;
		if (type == 'start') {
			DatetimeData.value = Number(new Date(formData.StartTime));
			PickerTitle.value = '开始时间';
		} else if (type == 'end') {
			DatetimeData.value = Number(new Date(formData.EndTime));
			PickerTitle.value = '结束时间';
		} else {
			DatetimeData.value = Number(new Date());
			PickerTitle.value = '';
		}
		console.log(DatetimeData.value);
		showTimePicker.value = true;

	}

	function ClosePicker() { // 关闭时间选择器
		DatetimeData.value = Number(new Date());
		showTimePicker.value = false;
	}

	function ConfirmTime(data : any) { // 确认时间
		console.log(data);
		let currentDate = new Date();
		let currentYear = currentDate.getFullYear(); // 获取年份

		let Start = '';
		let End = '';

		if (TimeType.value == 'start') {
			// 判断是否大于结束时间
			Start = currentYear + '-' + dateFormat(data.value);
			End = currentYear + '-' + formData.EndTime;

			if (new Date(Start) > new Date(End)) {
				return uni.showToast({
					title: '开始时间不能高于结束时间',
					icon: 'none'
				})
			}

			formData.StartTime = dateFormat(data.value);
			// that.$set(that.formData, 'StartTime', dateFormat(data.value));
		} else if (TimeType.value == 'end') {
			// 判断是否大于开始时间
			Start = currentYear + '-' + formData.StartTime;
			End = currentYear + '-' + dateFormat(data.value);

			if (new Date(Start) > new Date(End)) {
				return uni.showToast({
					title: '结束时间不能低于开始时间',
					icon: 'none'
				})
			}

			formData.EndTime = dateFormat(data.value);
			// that.$set(that.formData, 'EndTime', dateFormat(data.value));
		}
		showTimePicker.value = false;
	}

	function dateFormat(val : any, Type = 'yyyy-MM-dd  hh:mm') { // 格式化时间
		if (!uni.$utils.isEmpty(val)) {
			return uni.$utils.dateFormat(new Date(val), Type);
		} else {
			return uni.$utils.dateFormat(new Date(), Type);
		}
	}

	function ChangeDate() { // 报工时长输入框 input 事件

		let Hour = +formData.Hour;
		let Minute = +(String(formData.Minute).replace(/\D/g, ''));

		if (Minute >= 60) {
			Hour += Math.floor(Minute / 60);
			// $set(that.formData, 'Hour', String(Hour));
			// that.$set(that.formData, 'Minute', String(1));
			formData.Hour = String(Hour);
			formData.Minute = String(1);

			setTimeout(() => {
				formData.Minute = String(Minute % 60);
				// that.$set(that.formData, 'Minute', String(Minute % 60));
			}, 50)
		} else {
			formData.Minute = String(Minute);
			// that.$set(that.formData, 'Minute', String(Minute));
		}

		setTimeout(() => {
			let ManHour = Hour + Minute / 60;
			// that.$set(that.formData, 'ManHour', String(ManHour));
			formData.ManHour = String(ManHour);

			let GetDate = (+formData.Hour * 60 * 1000 * 60) + (+formData.Minute * 60 * 1000);

			if (uni.$utils.isEmpty(formData.EndTime)) { // 如果结束时间是空的
				// 设置结束时间为当前时间
				formData.EndTime = uni.$utils.dateFormat(new Date(), 'yyyy-MM-dd  hh:mm');

				let NewData = uni.$utils.dateFormat(Number(new Date(formData.EndTime)) - GetDate,
					'yyyy-MM-dd  hh:mm');

				formData.StartTime = NewData;
				// that.$set(that.formData, 'StartTime', NewData);
			} else {
				let NewData = uni.$utils.dateFormat(Number(new Date(formData.EndTime)) - GetDate,
					'yyyy-MM-dd  hh:mm');

				formData.StartTime = NewData;
				// that.$set(that.formData, 'StartTime', NewData);
			}

			uForm.value.validate();
		}, 800)
	}

	function BlurDateIpt(str : string) { // 报工时长输入框失焦事件
		switch (str) {
			case 'hour':
				formData.Hour = !uni.$utils.isEmpty(formData.Hour) ? formData.Hour : 0;
				break;
			case 'minute':
				formData.Minute = !uni.$utils.isEmpty(formData.Minute) ? formData.Minute : 0;
				break;
			default:
				break;
		}
	}

	function OpenChoiceDate() { // 点击报工时长箭头，打开选择时间弹层
		showTimePickerBG.value = true;
		// 拼接时间，打开弹层显示对应时间
		DatetimeDataBG.value = String(formData.Hour) + ':' + String(formData.Minute);
	}

	function formatter(type : string, data : any) { // 时间选择器数据格式化
		let value : any = +data;
		if (type === 'year') {
			return `${value}年`
		}
		if (type === 'month') {
			return `${value}月`
		}
		if (type === 'day') {
			return `${value}日`
		}
		if (type === 'hour') {
			if (value < 10) {
				value = '0' + value
			}
			return `${value}时`
		}
		if (type === 'minute') {
			if (value < 10) {
				value = '0' + value
			}
			return `${value}分`
		}
		return value
	}

	function ClosePickerBG() {
		showTimePickerBG.value = false;
	}

	function ConfirmTimeBG(data : any) { // 报工时长时间选择器确认按钮

		let TheData = data.value.split(':');
		let formattedArray = TheData.map((item : any) => parseInt(item));

		formData.Hour = String(formattedArray[0]);
		formData.Minute = String(formattedArray[1]);
		ChangeDate();

		ClosePickerBG();
	}

	/**
	 * 当获取到工单号或报工单号时，获取第一个工序
	 */
	function GetProcedureData() { // 获取工序

		request({
			config: {
			},
			url: 'XGD_GetAllPProceByWoOrJob',
			method: 'POST',
			data: {
				WoOrderID: formData.WoOrderID,
				JobOrderID: formData.JobOrderID || 0,
			}, success(ret : any) {
				if (ret.status == 200) {
					if (ret.data.ds.length) {
						let ProcessData : { [key : string] : any } = {};
						if (UserWorkshopID) {
							let filterData = ret.data.ds.filter((item : any) => {
								return item.FWorkshopID == UserWorkshopID;
							})
							if (filterData.length) {
								ProcessData = filterData[0];
							} else {
								ProcessData = ret.data.ds[0];
							}
						} else {
							ProcessData = ret.data.ds[0];
						}
						ProcessData['FNgQty'] = null;
						ProcessData['FDailyQtt'] = ProcessData['ReportQty'];

						formData = Object.assign(formData, ProcessData);
						uForm.value.validate();
					}
				}
			}
		});

	}

	function GetDroplist_Shift() {	// 开局默认选中班次

		request({
			config: {
			},
			url: 'Droplist_Shift',
			method: 'POST',
			data: {}, success(ret : any) {
				if (ret.status == 200) {
					if (ret.data.ds.length) {
						formData = Object.assign(formData, ret.data.ds[0]);
						uForm.value.validate();
					}
				}
			}
		});

	}

	function getEmplInfo() {

		let UserID = userStore.UserInfo.UserID;

		let sql = `select isnull(a.EmplID,0) as EmplID,isnull(b.EmplName,'') as EmplName
							from SYS_User a
							left join Hr_Employee b on a.EmplID=b.EmplID
							where a.UserID=${UserID}`;
		//console.log(sql);
		try {
			requestByUrl({
				config: {
					baseURL: '/SQLData/QuerySql'
				},
				url: '',
				method: 'POST',
				data: {
					sql: sql
				}, success(ret : any) {
					if (ret.status == 200) {
						FilterFormData.EmplIDData = JSON.parse(JSON.stringify(ret.data.ds));
						FilterFormData.EmplIDDataJoin = ret.data.ds.map((item : any) => item.EmplName).join(
							',');
						formData.EmplName = FilterFormData.EmplIDDataJoin;
						formData.EmplID = ret.data.ds.map((item : any) => item.EmplID).join(',');
					}
				}
			})

		} catch (e) {
			formData.EmplID = null;
			formData.EmplName = null;
		}
	}

	function selectClick(data : any) {

		let cloneObj = uni.$utils.deepClone(formData);
		// console.log(cloneObj)
		let ReservedFields = ['JobDocTypeName', 'JobDocTypeID'];

		isEdit.value = false; // 将状态却换成非编辑状态
		hasApprove.value = false; // 关闭审核
		console.log(data);
		// 连续报工,且未审核
		if (data.value == 1) {
			ReservedFields = ['FDailyQtt', 'FNgQty', 'FDailyOutputDeID', 'BGBillNo', 'BillNo']
		}

		Object.keys(formData).forEach((key) => {

			let arrayType = null;
			if (data.value == 1) {
				arrayType = ReservedFields.includes(key)
			} else if (data.value == 0) {

				arrayType = !ReservedFields.includes(key)
			}

			if (arrayType) {

				if (formData[key] == null) {
					formData[key] = null;
				} else if (Array.isArray(formData[key])) {
					formData[key] = [];
				} else if (typeof formData[key] === 'object') {
					formData[key] = {};
				} else {
					formData[key] = '';
				}
			}
		});
		if (data.value == 0) {
			InitFormData();
		}
	}

	function closeDevicePopup() {	// 关闭设备工序弹层
		showPopupByDevice.value = false;
		ScanByDeviceList.value = [];
		SelectScanByDeviseIndex.value = null;
	}

	function ChoiceProcedure_Config() {

		if (SelectScanByDeviseIndex.value != null) {
			let data = ScanByDeviceList.value[SelectScanByDeviseIndex.value];

			data['ReportQty'] = data['ReportQty'];
			// 获取选中项数据
			formData = Object.assign(formData, data);

			uForm.value.validate();
			closeDevicePopup();
		} else {
			uni.$utils.msg('请选中一项数据！', 1000);
		}

	}

	function ChoiceDeviceToProcedure(index : number) { // 点击设备工序弹层列表的某一项

		// 首先取消所有项的选中状态  
		ScanByDeviceList.value.forEach((item : any) => (item.checked = false));

		// 然后将点击的项设置为选中状态  
		ScanByDeviceList.value[index].checked = true;

		SelectScanByDeviseIndex.value = index;

	}

	function getMainInfoByDevice() {	// 扫码获取设备数据
		let parts : any = [];
		if (DeviceID.value != null)
			parts = DeviceID.value.split("|");

		uni.$utils.showLoading();

		try {
			// 扫设备带出可报工工序
			request({
				config: {
				},
				url: 'XGD_GetPROCByEquipment_2',
				method: 'POST',
				data: {
					EquipmentID: parts[1],
					QrCode: DeviceID.value,
					FCJType: FCJType.value
				},
				success(ret : any) {
					ScanByDeviceList.value = [];
					if (ret.status == 200) {
						showPopupByDevice.value = true;

						if (ret.data.ds.length && ret.data.ds[0].status != 500) {
							setTimeout(() => {

								interface DsItem {
									JobBillNO : string;
									[key : string] : any;
								}

								let data = (ret.data.ds as DsItem[]).map(item => {
									return {
										...item,
										checked: false,
										BillNO: item.JobBillNO
									}
								});
								paging.value.complete(data);
								uni.$utils.hideLoading();
							}, 500);
						} else {

							paging.value.complete([]);
							uni.$utils.hideLoading();
						}
					} else {
						uni.$utils.layer.alert(ret.data?.ds[0]?.msg);
					};
				},
				fail(error : any) {
					paging.value.complete([]);
					uni.$utils.layer.alert(JSON.stringify(error))
				}
			});

		} catch (e) {
			paging.value.complete([]);
			uni.$utils.hideLoading();
		}
	}

	function getMainInfo(val : any) {	// 扫码获取各类二维码信息

		let parts = val.split("|");

		if (parts[0] == 'PGD') {
			if (FCJType.value != 1) {
				return uni.$utils.msg('请扫描工单二维码')
			};

			request({
				config: {
				},
				url: 'Get_JobOrder',
				method: 'POST',
				data: {
					QrCode: val
				},
				success(ret : any) {
					if (ret.status == 200) {

						if (ret.data?.ds.length && ret.data?.ds[0]?.status == 500) {
							uni.$utils.msg(ret.data.ds[0].msg);
						} else {
							InitCreateFun();
							setTimeout(() => {
								formData.QrCode = val;
								formData = Object.assign(formData, ret.data.ds[0]);

								// 当前以选中 派工单号，获取工序
								GetProcedureData();

								uni.$utils.hideLoading(500);

								uForm.value.validate();
							}, 300)
						}
					} else {
						uni.$utils.layer.alert(ret.data?.ds[0]?.msg);
					}
				}
			});

		} else if (parts[0] == 'GD') {
			if (FCJType.value == 1) {
				return uni.$utils.msg('请扫描派工单二维码')
			};

			request({
				config: {
				},
				url: 'GD_WorkOrder',
				method: 'POST',
				data: {
					QrCode: val
				},
				success(ret : any) {
					if (ret.status == 200) {
						if (ret.data?.ds.length && ret.data?.ds[0]?.status == 500) {
							uni.$utils.msg(ret.data.ds[0].msg);
						} else {
							formData.QrCode = val;
							ret.data.ds[0]['QrCode'] = val;

							formData = Object.assign(formData, ret.data.ds[0]);

							// 当前以选中工单号 ，获取工序
							GetProcedureData();

							uForm.value.validate();
							uni.$utils.hideLoading(500);
						}
					} else {
						uni.$utils.layer.alert(ret.data?.ds[0]?.msg);
					}
				}
			});

		} else {

			// // 模具
			// let da2 = that.Request.PromiseRequest('PGD_GetMolud', {
			// 	// MoludCode: val, // 筛选条件
			// 	MoludID: parts[1], // 模具ID					
			// 	IsInStorage: 0,
			// 	PageIndex: 1,
			// 	PageSize: 30
			// });

			// // 设备
			// let da3 = that.Request.PromiseRequest('PGD_GetEquipment', {
			// 	EquipmentTypeID: formData.EquipmentTypeID || 0, // 类型ID
			// 	EquipmentCode: val, // 筛选条件
			// 	EquipmentID: formData.EquipmentID || 0, // 设备ID
			// });


			// da2.promise.then((data) => { // 模具

			// 	if (that.$utils.isEmpty(that.formData.ProcedureID)) {
			// 		that.$utils.hideLoading();
			// 		uni.showToast({
			// 			title: '请选择工序',
			// 			icon: 'none'
			// 		});
			// 		throw new Error('请选择工序');
			// 	};
			// 	console.log(data)
			// 	if (data.data.ds.length > 0 && data.data.ds[0].status == 500) {
			// 		return da3.promise
			// 	} else {
			// 		that.$utils.hideLoading(500);
			// 		if (data.data.ds.length > 0) {
			// 			that.formData = Object.assign(that.formData, data.data.ds[0]);
			// 			that.$utils.hideLoading(500);
			// 		} else {
			// 			that.$utils.hideLoading();
			// 			uni.showToast({
			// 				title: data.data.ds1[0].MSG,
			// 				icon: 'none'
			// 			})
			// 		}
			// 		throw new Error('终止条件满足');
			// 	}
			// }).then((result) => { // 设备
			// 	da2 = null;
			// 	if (that.$utils.isEmpty(that.formData.ProcedureID)) {
			// 		that.$utils.hideLoading();
			// 		uni.showToast({
			// 			title: '请选择工序',
			// 			icon: 'none'
			// 		});
			// 		throw new Error('请选择工序');
			// 	};
			// 	// console.log(result)
			// 	if (result.data.ds.length && result.data.ds[0].status == 500) {
			// 		that.$utils.hideLoading();
			// 		uni.showToast({
			// 			title: '请扫描正确的二维码'
			// 		})
			// 	} else {
			// 		// console.log(result)

			// 		if (result.data.length) {
			// 			that.formData = Object.assign(that.formData, result.data);
			// 			that.$utils.hideLoading(500);
			// 		} else {
			// 			that.$utils.hideLoading();
			// 			uni.showToast({
			// 				title: '请扫描正确的二维码',
			// 				icon: 'none'
			// 			})
			// 		}

			// 		throw new Error('终止条件满足');
			// 	}
			// }).catch((err : any) => {
			// 	// console.log(err)
			// 	uni.$utils.hideLoading();
			// 	if (err.status == 500) {
			// 		uni.showToast({
			// 			title: '请扫描正确的二维码',
			// 			icon: 'none'
			// 		})
			// 	}
			// })
		}
	}

	function OpenScanBtn() {	// 扫码按钮
		uni.$utils.$scanPopup.openScan({
			success: (res) => {
				console.log(res);

				function startsWithEQRegex(str : string) {
					return /^EQ/.test(str) || /^SB/.test(str);
				}

				// 判断扫描的二维码是否为设备二维码
				let IsDevice = startsWithEQRegex(res.result)
				if (IsDevice) {
					// 如果是设备二维码，获取该设备的派工单数据
					DeviceID.value = res.result;
					getMainInfoByDevice();
				} else {
					getMainInfo(res.result);
				}
			}
		})
	}

	let routes = getCurrentPages(); //当前页面栈

	const baseScreenListenName = computed(() => {
		return 'createWorks_choice_' + routes.length
	});

	function openBaseScreen(str : string, type : string) {	// 前往筛选页
		switch (type) {
			case "radio":

				switch (str) {
					case '工单号':
						mainStore.openBaseScreen({
							allowClear: false, // 清除按钮
							cmd: 'XGD_BGWorkOrder', // 接口名
							titleName: str,
							listeningName: baseScreenListenName.value, // 监听器
							serverSearch: { // 查询项
								format: { // 数据映射
									displayValue: "WoBillNO", // 显示值
									hiddenValue: "WoBillNO", // 隐藏值
									pageIndex: "PageIndex", // 分页状态页码字段
									pageSize: "PageSize", // 分页状态每页数量字段
								},
								isLocal: false, // 是否启用本地数据
								localData: [], // 当开启本地数据时使用
								isPaging: true, //是否分页
								searchKey: 'BillNO', //搜索关键词，应包含在param中
								subText: [{
									label: "", // label文本
									labelKey: "ProductCode", // 显示label文本后文字的key
								}],
								choiceData: formData.WoBillNO, // 选中数据
								choiceDataKey: "WoBillNO", // 选中数据的key
								isTree: false, // 是否开启树型下拉
							},
							param: { // 传递参数
								BillNO: '',
								FCJType: FCJType.value,
								PageIndex: 1,
								PageSize: 30
							}
						});
						break;
					case '派工单号':
						mainStore.openBaseScreen({
							allowClear: false, // 清除按钮
							cmd: 'XGD_BGJobOrder', // 接口名
							titleName: str,
							listeningName: baseScreenListenName.value, // 监听器
							serverSearch: { // 查询项
								format: { // 数据映射
									displayValue: "JobBillNO", // 显示值
									hiddenValue: "JobOrderID", // 隐藏值
									pageIndex: "PageIndex", // 分页状态页码字段
									pageSize: "PageSize", // 分页状态每页数量字段
								},
								isLocal: false, // 是否启用本地数据
								localData: [], // 当开启本地数据时使用
								isPaging: true, //是否分页
								searchKey: 'BillNO', //搜索关键词，应包含在param中
								subText: [{
									label: "", // label文本
									labelKey: "ProductCode", // 显示label文本后文字的key
								}],
								choiceData: formData.JobOrderID, // 选中数据
								choiceDataKey: "JobOrderID", // 选中数据的key
								isTree: false, // 是否开启树型下拉
							},
							param: { // 传递参数
								BillNO: '',
								FCJType: FCJType.value,
								PageIndex: 1,
								PageSize: 30
							}
						});
						break;
					case '报工类型':
						if (!uni.$utils.isEmpty(formData.BGBillNo)) return;
						mainStore.openBaseScreen({
							allowClear: false,
							cmd: 'PGD_GetBGType',
							titleName: str,
							listeningName: baseScreenListenName.value,
							serverSearch: {
								format: {
									displayValue: "TypeName",
									hiddenValue: "JobDocTypeID",
								},
								choiceData: formData.JobDocTypeID, // 选中数据
								choiceDataKey: "JobDocTypeID", // 选中数据的key
							},
							param: {}
						});
						break;
					case '生产车间':
						mainStore.openBaseScreen({
							allowClear: false,
							cmd: 'XGD_Workshop',
							titleName: str,
							listeningName: baseScreenListenName.value,
							serverSearch: {
								format: {
									displayValue: "FWorkshopName",
									hiddenValue: "JobDocTypeID",
									pageIndex: "PageIndex", // 分页状态页码字段
									pageSize: "PageSize", // 分页状态每页数量字段
								},
								isPaging: true, //是否分页
								searchKey: 'SearchKey', //搜索关键词，应包含在param中
								subText: [{
									label: "", // label文本
									labelKey: "ProductCode", // 显示label文本后文字的key
								}],
								choiceData: formData.FWorkshopID, // 选中数据
								choiceDataKey: "FWorkshopID", // 选中数据的key
							},
							param: {
								SearchKey: '',
								PageIndex: 1,
								PageSize: 30
							}
						});
						break;
					case '工序':
						if (uni.$utils.isEmpty(formData.FWorkshopID)) {
							return uni.showToast({
								title: '请选择生产车间',
								icon: 'none'
							});
						};
						mainStore.openBaseScreen({
							allowClear: false,
							cmd: 'XGD_GetAllPProceByWoOrJob',
							titleName: str,
							listeningName: baseScreenListenName.value,
							serverSearch: {
								format: {
									displayValue: "ProcedureName",
									hiddenValue: "ProcedureID",
								},
								subText: [{
									label: '派工单号：',
									labelKey: 'JobBillNO'
								}, {
									label: '工单号：',
									labelKey: 'WoBillNO'
								}, {
									label: '产品：',
									labelKey: 'ProductName'
								}, {
									label: '可报数量：',
									labelKey: 'ReportQty'
								}],
								choiceData: formData.ProcedureID, // 选中数据
								choiceDataKey: "ProcedureID", // 选中数据的key
							},
							param: {
								WoOrderID: formData.WoOrderID,
								JobOrderID: formData.JobOrderID,
							}
						});
						break;
					case '模具编号':
						if (uni.$utils.isEmpty(formData.ProcedureID)) {
							return uni.showToast({
								title: '请选择工序',
								icon: 'none'
							});
						}
						mainStore.openBaseScreen({
							allowClear: false,
							cmd: 'PGD_GetMolud',
							titleName: str,
							listeningName: baseScreenListenName.value,
							serverSearch: {
								format: {
									displayValue: "MoludCode",
									hiddenValue: "MoludID",
									pageIndex: "PageIndex", // 分页状态页码字段
									pageSize: "PageSize", // 分页状态每页数量字段
								},
								isPaging: true, //是否分页
								searchKey: 'MoludCode', //搜索关键词，应包含在param中
								choiceData: formData.MoludID, // 选中数据
								choiceDataKey: "MoludID", // 选中数据的key
							},
							param: {
								MoludCode: '', // 筛选条件
								MoludID: 0, // 模具ID 
								IsInStorage: 0,
								PageIndex: 1,
								PageSize: 30
							}
						});
						break;
					case '设备':
						if (uni.$utils.isEmpty(formData.ProcedureID)) {
							return uni.showToast({
								title: '请选择工序',
								icon: 'none'
							});
						};
						mainStore.openBaseScreen({
							allowClear: false,
							cmd: 'PGD_GetEquipment',
							titleName: str,
							listeningName: baseScreenListenName.value,
							serverSearch: {
								format: {
									displayValue: "EquipmentCode",
									hiddenValue: "EquipmentID",
								},
								searchKey: 'EquipmentCode', //搜索关键词，应包含在param中
								choiceData: formData.EquipmentID, // 选中数据
								choiceDataKey: "EquipmentID", // 选中数据的key
							},
							param: {
								EquipmentTypeID: formData.EquipmentTypeID || 0, // 类型ID
								EquipmentCode: '', // 筛选条件
								EquipmentID: formData.EquipmentID || 0, // 设备ID
							}
						});
						break;
					case '班次':
						mainStore.openBaseScreen({
							allowClear: false,
							cmd: 'Droplist_Shift',
							titleName: str,
							listeningName: baseScreenListenName.value,
							serverSearch: {
								format: {
									displayValue: "ShiftName",
									hiddenValue: "ShiftID",
								},
								choiceData: formData.ShiftID, // 选中数据
								choiceDataKey: "ShiftID", // 选中数据的key
							},
							param: {}
						});
						break;
					case '计时计件':
						mainStore.openBaseScreen({
							allowClear: false,
							cmd: '',
							titleName: str,
							listeningName: baseScreenListenName.value,
							serverSearch: {
								format: {
									displayValue: "PieceTimeName",
									hiddenValue: "PieceTime",
								},
								isLocal: true, // 是否启用本地数据
								localData: PieceTimeNameData,
								choiceData: formData.PieceTime, // 选中数据
								choiceDataKey: "PieceTime", // 选中数据的key
							},
							param: {}
						});
						break;
					default:
						break;
				}

				break;

			case "check":
				switch (str) {
					case '作业员':
						mainStore.openBaseScreen({
							allowClear: false,
							cmd: 'XGD_Employee',
							titleName: str,
							listeningName: baseScreenListenName.value,
							multiple: true,
							serverSearch: {
								format: {
									displayValue: "EmplName",
									hiddenValue: "EmplID",
									pageIndex: "PageIndex", // 分页状态页码字段
									pageSize: "PageSize", // 分页状态每页数量字段
								},
								isPaging: true, //是否分页
								searchKey: 'EmplCode', //搜索关键词，应包含在param中
								choiceData: FilterFormData.EmplIDData, // 选中数据
								choiceDataKey: 'EmplID' // 选中数据的key
							},
							param: {
								EmplCode: '',
								PageIndex: 1,
								PageSize: 30,
								FWorkshopID: formData.FWorkshopID || 0
							}
						});
						break;
					default: break;
				}

				break;

			default: break;
		}
	}

	onLoad((option : any) => {
		if (!uni.$utils.isEmpty(option)) {
			if (option.Edit == 'isEdit') {
				isEdit.value = true;
			}
			formData.FDailyOutputDeID = option.FDailyOutputDeID;
			GetEchoData(option.FDailyOutputDeID);
		} else {
			InitFormData();
			// formData.FDailyOutputDeID = 0;
			// isEdit.value = false;
			// enabledSubmitBtn.value = true;
		}
	});

	onReady(() => {
		uni.$on(baseScreenListenName.value, (ret : any) => {
			console.log(ret);
			const { titleName } = ret;

			switch (titleName) {
				case '工单号':
					InitCreateFun();
					setTimeout(() => {
						ret.data['BillNO'] = ret.data['JobBillNO'];
						console.log(formData);
						formData = Object.assign(formData, ret.data);

						// 当前以选中工单号、派工单号，获取工序
						GetProcedureData();
						// uForm.value.validate();
					}, 300);
					break;
				case '派工单号':
					InitCreateFun();
					setTimeout(() => {
						ret.data['BillNO'] = ret.data['JobBillNO'];
						formData = Object.assign(formData, ret.data);
						// 当前以选中工单号、派工单号，获取工序
						GetProcedureData();
						// uForm.value.validate();
					}, 300);
					break;
				case '报工类型':
					formData.JobDocTypeName = ret.data.TypeName;
					formData.JobDocTypeID = ret.data.JobDocTypeID;
					break;
				case '生产车间':
					formData.FWorkshopName = ret.data.FWorkshopName;
					formData.FWorkshopID = ret.data.FWorkshopID;
					break;
				case '工序':
					ret.data['FNgQty'] = null;
					ret.data['FDailyQtt'] = ret.data['ReportQty'];
					formData = Object.assign(formData, ret.data);
					break;
				case '模具编号':
					formData = Object.assign(formData, ret.data);
					break;
				case '设备':
					formData = Object.assign(formData, ret.data);
					break;
				case '班次':
					formData = Object.assign(formData, ret.data);
					break;
				case '作业员':
					FilterFormData.EmplIDData = JSON.parse(JSON.stringify(ret.data));
					FilterFormData.EmplIDDataJoin = ret.data.map((item : any) => item.EmplName).join(',');
					formData.EmplName = FilterFormData.EmplIDDataJoin;
					formData.EmplID = ret.data.map((item : any) => item.EmplID).join(',');
					break;
				case '计时计件':
					formData = Object.assign(formData, ret.data);
					break;
				default:
					break;
			}

			uForm.value.validate();
		});
	});

	onMounted(() => {

		// #ifdef MP-WEIXIN
		uForm.value.setRules(rules)
		// #endif

		nextTick(() => {
			enabledSubmitBtn.value = true;
			BtnShow.value = true;
		})
	})



	onUnload(() => {
		uni.$off(baseScreenListenName.value);
	});
</script>

<style lang="scss" scoped>
	.page__content {
		height: 100vh;
		display: flex;
		flex-direction: column;

		&__main {
			flex: 1;
			overflow: auto;
			// padding: 0 20rpx;
			background-color: #f9f9f9;
		}

		:deep(.u-form) {
			padding: 0 20rpx;
			background-color: #fff;

			.iptView {
				width: 100%;
			}

			// 处理 up-input 在小程序下样式穿透
			:deep(.u-input) {
				font-size: 28rpx;
				width: 100% !important;
			}
		}

		&__time-choice {
			display: flex;
			flex-direction: column;
			margin-top: 10rpx;
		}

		&__time-box {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		&__time-start,
		&__time-end {
			flex: 1;
			display: flex;
			flex-direction: column;
			color: #333;
			font-size: 28rpx;
		}

		&__time-icon {
			margin: 0 20rpx;
		}

		&__materials {
			display: flex;
			align-items: center;
			font-size: 15px;
			color: #333;
		}

		&__materials-count {
			color: #51d0d0;
			font-weight: 600;
			margin: 0 8rpx;
			font-size: 15px;
		}

		&__materials-empty {
			color: #999;
			font-size: 14px;
		}

		&__btns {
			padding: 6px 15px;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			background-color: #fff;
		}

		&__btn {
			width: 80%;

			&--primary {
				background-color: #51d0d0;
				color: #fff;
			}
		}


	}
</style>